package cn.chenhao.pet.service.impl;

import cn.chenhao.basic.service.impl.BasicServiceImpl;
import cn.chenhao.pet.domain.Pet;
import cn.chenhao.pet.domain.PetDetail;
import cn.chenhao.pet.mapper.PetDetailMapper;
import cn.chenhao.pet.mapper.PetMapper;
import cn.chenhao.pet.service.IPetService;
import cn.chenhao.user.domain.User;
import cn.chenhao.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PetServiceImpl  extends BasicServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private PetDetailMapper petDetailMapper;

    @Autowired
    private UserMapper userMapper;

    @Transactional
    @Override
    public void add(Pet pet) {
        // 保存宠物基本信息
        petMapper.save(pet);
        // 保存宠物详情
        PetDetail detail = pet.getDetail();
        if (detail != null){
            detail.setPet_id(pet.getId());
            petDetailMapper.save(detail);
        }
    }

    /**
     * 上架操作
     * @param ids
     */
    @Override
    public void onSale(List<Long> ids) {
        Map<String,Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("onSaleTime", new Date());
        petMapper.onSale(map);

    }

    /**
     * 下架操作
     * @param ids
     */
    @Override
    public void offSale(List<Long> ids) {
        Map<String,Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("offSaleTime", new Date());
        petMapper.offSale(map);
    }

    /**
     * 领养
     * @param id
     * @param loginId
     */
    @Override
    public void adoptPet(Long id, Long loginId) {
        // 根据id获取当前宠物信息
        Pet pet = petMapper.loadById(id);
        // 查询领养的登录人信息
        User user = userMapper.loadByLogininfoId(loginId);
        // 设置当前宠物的领养人id
        pet.setUser_id(user.getId());
        // 将宠物状态设置为下架
        pet.setState(0);
        // 设置下架时间
        pet.setOffsaletime(new Date());
        // 修改
        petMapper.update(pet);
    }

}
